package cn.sjtu.security.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static cn.sjtu.security.utils.GlobalConstants.LOGIN_CAPTCHA_CODE;

/**
 * 生成验证码
 */
@Controller
@Slf4j
public class CodeController {

    @Autowired
    private HttpServletRequest request;

    /**
     * 利用hutool工具获取验证码图片
     * @param response
     * @throws IOException
     */
    @GetMapping("/code/image")
    public void getCode(HttpServletResponse response) throws IOException {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        String code = circleCaptcha.getCode();
        log.info("验证码为：{}", code);
        request.getSession().setAttribute(LOGIN_CAPTCHA_CODE, code);
        response.setContentType("image/jpeg");
        ImageIO.write(circleCaptcha.getImage(), "jpeg", response.getOutputStream());
    }
}
